package com.zhixi100.orderservice.service;

import com.zhixi100.framework.common.ObjectRestResponse;
import com.zhixi100.orderservice.entity.Order;
import com.zhixi100.orderservice.feign.ProductFeign;
import com.zhixi100.orderservice.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * author:tommy
 * date:2018/12/13
 */
@Slf4j
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductFeign productFeign;

    public Order findById(int id) {
        return orderMapper.findById(id);
    }

    @Transactional(readOnly = false)
    public Order saveOrder(Object obj, int productId) {
        Order order = new Order();
        ObjectRestResponse res = productFeign.findProduct(productId);

        Map user = obj == null ? null : (Map) obj;

        Map product = (Map) res.getData();
        if (product != null && user != null) {
            log.info("map::::" + product.toString());
            log.info("productName::::" + product.get("productName").toString());
            log.info("price::::" + product.get("price").toString());
            order.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
            order.setProductId(productId);
            order.setProductName(product.get("productName").toString());
            order.setPrice(new BigDecimal(product.get("price").toString()));
            order.setUserId(Integer.parseInt(user.get("id").toString()));
            order.setCreateDate(new Date());
        }

        orderMapper.insertOrder(order);

        //减库存
        productFeign.reduceStore(productId);

        return order;
    }
}
